import { IQueryParams } from '@/widgets/table-pagination';
import * as api from './dictionary-api';
import { IReducerState } from '@/store/root-reducer';

export const fetchItems = async (queryParams: IQueryParams, dispatch: any) => {
  dispatch({
    type: 'start',
    name: 'dictionary',
  });
  try {
    const response = await api.getList(queryParams);
    console.log('fetch dictionary items', response);
    const { content: entities, totalElements: totalCount } = response.data;
    if (entities.length === 0 && queryParams.pageNum > 1) {
      const _response = await api.getList({
        ...queryParams,
        pageNum: queryParams.pageNum - 1,
      });
      const {
        data: { content, totalElements },
      } = _response.data;
      dispatch({
        type: 'entitiesFetched',
        name: 'dictionary',
        payload: {
          totalCount: totalElements,
          entities: content,
          offset: (queryParams.pageNum - 1) * queryParams.pageSize,
        },
      });
    } else {
      dispatch({
        type: 'entitiesFetched',
        name: 'dictionary',
        payload: {
          totalCount,
          entities,
          offset: (queryParams.pageNum - 1) * queryParams.pageSize,
        },
      });
    }
    // return entities;
  } catch (err) {
    console.log('err', err);
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  }
};

export const setItem = async (
  key: any,
  dispatch: any,
  state: IReducerState
) => {
  const entityIdx = state.entities?.findIndex((e) => e[state.key] == key);
  if (entityIdx != -1) {
    dispatch({
      type: 'entitySet',
      name: 'dictionary',
      payload: {
        entity: state.entities[entityIdx],
        index: entityIdx,
      },
    });
  }
};

export const clearItem = async (dispatch: any, state: any) => {
  dispatch({
    type: 'entitySet',
    name: 'dictionary',
    payload: {
      entity: null,
      index: -1,
    },
  });
};

export const nextItem = async (
  dispatch: any,
  state: IReducerState,
  curQueryParams?: IQueryParams
) => {
  dispatch({
    type: 'start',
    name: 'dictionary',
  });
  try {
    if (state.index + state.offset >= state.totalCount - 1) {
      return false;
    } else {
      // 本地获取下一个
      let nextEntityIdx = state.index + 1;
      let nextEntity = state.entities[nextEntityIdx];

      // 远程获取下一个
      if (!nextEntity && curQueryParams != null) {
        const newQueryParams = {
          ...curQueryParams,
          pageNum: state.offset + state.index + 2,
          pageSize: 1,
        };
        const response = await api.getList(newQueryParams);
        const { items } = response.data;
        if (items && items.length > 0) {
          nextEntityIdx = state.index + 1;
          nextEntity = items[0];
        }
      }
      if (nextEntityIdx != undefined && nextEntity) {
        dispatch({
          type: 'entitySet',
          name: 'dictionary',
          payload: {
            entity: nextEntity,
            index: nextEntityIdx,
          },
        });
        return nextEntity[state.key];
      } else {
        return null;
      }
    }
  } catch (err) {
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  } finally {
    dispatch({
      type: 'end',
      name: 'dictionary',
    });
  }
};

export const prevItem = async (
  dispatch: any,
  state: IReducerState,
  curQueryParams?: IQueryParams
) => {
  dispatch({
    type: 'start',
    name: 'dictionary',
  });
  try {
    if (state.index + state.offset <= 0) {
      return false;
    } else {
      // 本地获取上一个
      let prevEntityIdx = state.index - 1;
      let prevEntity = state.entities[prevEntityIdx];

      // 远程获取上一个
      if (!prevEntity && curQueryParams != null) {
        const newQueryParams = {
          ...curQueryParams,
          pageNum: state.offset + state.index,
          pageSize: 1,
        };
        const response = await api.getList(newQueryParams);
        const { items } = response.data;
        if (items && items.length > 0) {
          prevEntityIdx = state.index - 1;
          prevEntity = items[0];
        }
      }

      if (prevEntityIdx != undefined && prevEntity) {
        dispatch({
          type: 'entitySet',
          name: 'dictionary',
          payload: {
            entity: prevEntity,
            index: prevEntityIdx,
          },
        });
        return prevEntity[state.key];
      } else {
        return null;
      }
    }
  } catch (err) {
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  } finally {
    dispatch({
      type: 'end',
      name: 'dictionary',
    });
  }
};

export const createItem = async (entity: any, dispatch: any) => {
  try {
    const response = await api.createItem(entity);
    const { data: success } = response.data;

    if (success) {
      dispatch({
        type: 'entityCreated',
        name: 'dictionary',
        payload: {
          entity: success,
        },
      });
    }

    return success;
  } catch (err) {
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  }
};

export const updateItem = async (entity: any, dispatch: any) => {
  try {
    const response = await api.updateItem(entity);
    const { data: success } = response.data;

    if (success) {
      dispatch({
        type: 'entityUpdated',
        name: 'dictionary',
        payload: {
          entity,
        },
      });
    }

    return success;
  } catch (err) {
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  }
};

export const deleteItem = async (key: any, dispatch: any) => {
  dispatch({
    type: 'start',
    name: 'dictionary',
  });
  try {
    const response = await api.deleteItem(key);
    const { data: success } = response.data;

    if (success) {
      dispatch({
        type: 'entityDeleted',
        name: 'dictionary',
        payload: {
          key,
        },
      });
    }

    return success;
  } catch (err) {
    dispatch({
      type: 'catchError',
      name: 'dictionary',
      payload: {
        err,
      },
    });
  }
};
